<?php
class Apis{
  protected static $_instance;
  private $inited;
  private $urls;
	private function __construct(){}
	private function __clone(){}
	public static function inst($conf=false){
	  if( null===self::$_instance ){
	    self::$_instance=new self();
		}
		if($conf) self::$_instance->init($conf);
		return self::$_instance;
	}

	protected $errors=array('err'=>array(),'wrn'=>array());
	protected function error($msg){ $this->errors['err'][]=$msg; return false;}
	protected function warning($msg){ $this->errors['wrn'][]=$msg; return false;}
	public function getError(){ return $this->errors['err'][ count($this->errors['err'])-1 ]; }
	public function getErrors(){ return $this->errors['err']; }
	public function getWarning(){ return $this->errors['wrn'][ count($this->errors['wrn'])-1 ]; }
	public function getWarnings(){ return $this->errors['wrn']; }
	
	public function init($conf){
	  if( $this->inited ) return true;
	  $this->urls=include_once $_SERVER['DOCUMENT_ROOT'].$conf;
	  $this->inited=true;
	}
	
	public function invoke($apiId,$path='',$method='GET',$data=array()){
	  if( !$this->inited ) return $this->error('Not inited');
	  if( empty($this->urls[$apiId]) ) return $this->error('Api not found');
	  if($method=='GET')
	  	$rs=$this->makeGet($this->urls[$apiId].$path);
	  elseif($method=='POST')
	    $rs=$this->makePost($this->urls[$apiId].$path,$data);

		//$rs=json_decode($rs);
		
		if(!empty( $rs->error )) return $this->error($rs->error);
	  return $rs;
	}
	
	protected function makeGet($req='/',$headers=array()){
  	$context = stream_context_create(
			array(
			  'http'=>array(
			    'method'=>'GET',
			    'header'=> (!empty($headers))?implode("\r\n",$headers):''
			  )
			)
		);
		try{
		  $json=@file_get_contents($req, false, $context);
	  }catch(Exception $e){
	    return false;
		}
	  return json_decode($json);
	}
	protected function makePost($req='/',$data,$headers=array()){
  	$context = stream_context_create(
			array(
			  'http'=>array(
			    'method'=>'POST',
			    'header'=> (!empty($headers))?implode("\r\n",$headers):'',
			    'content' => http_build_query($data),
			  )
			)
		);
		try{
	  	$json=@file_get_contents($req, false, $context);
	  }catch(Exception $e){
	    return false;
		}
	  return json_decode($json);
	}
}
?>
